//
//  JJHttpClient.m
//  jiajia
//
//  Created by rujia chen on 16/5/1.
//  Copyright © 2016年 sunrisin. All rights reserved.
//

#import "JJHttpClient.h"
#import <AFNetworking/AFNetworking.h>

@interface JJHttpClient ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

static const NSString *kErrorMessageKey = @"errmsg";
static const NSString *kErrorCodeKey = @"errcode";
@implementation JJHttpClient

+ (JJHttpClient *)client {
    static JJHttpClient *client = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        client = [[self alloc] init];
    });
    
    return client;
}

- (instancetype)init {
    if (self = [super init]) {
        self.manager = [AFHTTPSessionManager manager];
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [self.manager.requestSerializer setValue:[UIDevice currentDevice].isPad?@"1":@"0" forHTTPHeaderField:@"x-ua"];
        [self.manager.requestSerializer setTimeoutInterval:15];
        NSString *sessionid = [[NSUserDefaults standardUserDefaults] objectForKey:UDKeyForSessionID];
        if (sessionid) {
            [self.manager.requestSerializer setValue:sessionid forHTTPHeaderField:@"x-sid"];
        }
    }
    
    return self;
}

- (void)addValue:(id)value forHTTPHeaderField:(NSString *)field {
    [self.manager.requestSerializer setValue:value forHTTPHeaderField:field];
}

- (NSDictionary*)allHTTPRequestHeader {
    return self.manager.requestSerializer.HTTPRequestHeaders;
}

- (NSString *)hostName {
    return @"http://www.sunrisin.com:8088";
}

- (NSURLSessionTask *)GET:(NSString *)url params:(NSDictionary *)params successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    LogGray(@"\n🚀[request]%@\n%@",url, [params jj_jsonString]);
    NSURLSessionTask *task = [self.manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleRequestSuccessWithTask:task andResponse:responseObject andSuccessBlock:successBlock failBlock:failBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self handleRequestFailWithTask:task andError:error andExceptionBlock:exceptionBlock];
    }];
    
    return task;
}

- (NSURLSessionTask *)POST:(NSString *)url params:(NSDictionary *)params successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    LogGray(@"\n🚀[request]%@\n%@",url, [params jj_jsonString]);
    NSURLSessionTask *task = [self.manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleRequestSuccessWithTask:task andResponse:responseObject andSuccessBlock:successBlock failBlock:failBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self handleRequestFailWithTask:task andError:error andExceptionBlock:exceptionBlock];
    }];
    
    return task;
}

- (NSURLSessionTask *)PUT:(NSString *)url params:(NSDictionary *)params successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    LogGray(@"\n🚀[request]%@\n%@",url, [params jj_jsonString]);
    NSURLSessionTask *task = [self.manager PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleRequestSuccessWithTask:task andResponse:responseObject andSuccessBlock:successBlock failBlock:failBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self handleRequestFailWithTask:task andError:error andExceptionBlock:exceptionBlock];
    }];
    
    return task;
}

- (NSURLSessionTask *)DELETE:(NSString *)url params:(NSDictionary *)params successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    LogGray(@"\n🚀[request]%@\n%@",url, [params jj_jsonString]);
    NSURLSessionTask *task = [self.manager DELETE:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleRequestSuccessWithTask:task andResponse:responseObject andSuccessBlock:successBlock failBlock:failBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self handleRequestFailWithTask:task andError:error andExceptionBlock:exceptionBlock];
    }];
    
    return task;
}

#pragma mark - private

- (void)handleRequestSuccessWithTask:(NSURLSessionTask*)task andResponse:(id)responseObject andSuccessBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock{
    NSString *errmsg = nil;
    NSInteger errcode = 0;
    if (![[responseObject allKeys] containsObject:kErrorMessageKey]) {
        LogGreen(@"\n💪[response]%@\n%@",task.currentRequest.URL.standardizedURL, [responseObject jj_jsonString]);
        if (successBlock) successBlock(task,responseObject);
    }else {
        LogRed(@"\n😢[response]%@\n%@", task.currentRequest.URL.standardizedURL, [responseObject jj_jsonString]);
        errmsg = responseObject[kErrorMessageKey];
        errcode = [responseObject[kErrorCodeKey] integerValue];
        if (failBlock) failBlock(task, errcode , errmsg);
    }
}

- (void)handleRequestFailWithTask:(NSURLSessionTask*)task andError:(NSError*)error andExceptionBlock:(ExceptionBlock)exceptionBlock{
    LogRed(@"\n😂[error]%@\n%@", task.currentRequest.URL.standardizedURL, error.description);
    if (exceptionBlock) exceptionBlock(task, error);
}
@end
